<template>
  <el-dialog
    title='新增隐患排查基本信息'
    width="40%"
    :visible.sync='state'
    :modal-append-to-body='false'
    :close-on-click-modal='false'
    :close-on-press-escape='false'
    @close='closeBox'>

    <el-form :model='form' :rules='rules' ref='form' size='small'>
      <el-row type='flex' class='row-bg' justify='space-between' align='middle'>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='企业名称：' :label-width='formLabelWidth' prop='checkedId'>
            <el-select size='medium' v-model='form.checkedId' placeholder='请选择企业名称'>
              <el-option v-for='item in companyList' :key='item.id' :label='item.name' :value='item.id'>{{ item.name }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='巡查时间：' :label-width='formLabelWidth' prop='checkTime'>
            <el-date-picker style='width: 100%' v-model='form.checkTime' type='datetime' format='yyyy-MM-dd HH:mm:ss' placeholder='请选择巡查时间'>
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='记录文件：' :label-width='formLabelWidth' prop='attachmentIdAttr'>
            <el-upload class='oss-upload' ref='upload' action=''
                       :multiple='true'
                       :file-list='form.attachmentIdAttr'
                       :on-remove='handleRemove1'
                       :on-change='handleChange1'
                       :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='巡排查结果：' :label-width='formLabelWidth' prop='state'>
            <el-radio-group v-model='form.state'>
              <el-radio :label='true'>合格</el-radio>
              <el-radio :label='false'>不合格</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if='!form.state'>
        <div v-for='(item, index) in checkItems' :key='index' style='margin-bottom: 10px'>
          <el-row :gutter='12'>
            <el-card shadow='always'>
              <el-col :span='24'>
                <el-row justify='space-around' align='middle'>
                  <el-col :span='10'>
                    <el-form-item :label="'隐患问题'+(index+1)+'：'" label-width='90px' prop='name'>
                      <el-input size='small' v-model='item.name' autocomplete='off'></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span='10'>
                    <el-form-item label='整改期限：' label-width='90px' prop='rectifyDeadline'>
                      <el-date-picker style='width: 100%' v-model='item.rectifyDeadline' type='datetime' format='yyyy-MM-dd HH:mm:ss' placeholder='请选择整改期限'></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span='24' justify='space-around'>
                <el-row>
                  <el-col :span='10'>
                    <el-form-item label='整改结果：' label-width='90px' prop='resultState'>
                      <el-select size='medium' v-model='item.resultState' placeholder='请选择整改结果'>
                        <el-option v-for='itemc in resultStateList' :key='itemc.value' :label='itemc.name' :value='itemc.value'>{{ itemc.name }}</el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span='10'>

                    <el-form-item label='整改建议：' label-width='90px' prop='reformProposalAttr'>
                      <el-upload class='oss-upload' ref='upload' action=''
                                 :multiple='true'
                                 :file-list='item.reformProposalAttr'
                                 :on-remove="handleRemoveDynamic.bind(null, {'index': index,'data': item})"
                                 :on-change="handleChangeDynamic.bind(null, {'index': index,'data': item})"
                                 :auto-upload='false'>
                        <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
                        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
                        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                      </el-upload>
                    </el-form-item>

                  </el-col>
                  <el-col :span='2'>
                    <el-button @click='addItem()' v-if='index == checkItems.length - 1' type='primary' icon='el-icon-plus'></el-button>
                    <el-button @click='delItem(index)' v-else type='danger' icon='el-icon-close'></el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-card>
          </el-row>
        </div>

        <el-row type='flex' class='row-bg' justify='start'>
          <el-col :span='24' class='grid-content'>
            <el-form-item label='整改报告：' label-width='90px' prop='reportIdAttr'>
              <el-upload class='oss-upload' ref='upload' action=''
                         :multiple='true'
                         :file-list='form.reportIdAttr'
                         :on-remove='handleRemove2'
                         :on-change='handleChange2'
                         :auto-upload='false'>
                <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
                <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-divider></el-divider>
      <el-row justify='end' align='middle'>
        <el-col :span='24'>
          <el-form-item style='float: right'>
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type='primary' @click="submit('form')">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>

import UploadFiles from '@/components/uploadFiles/UploadFiles';

export default {
  components: {
    UploadFiles,
  },
  computed: {},
  data() {
    return {
      formLabelWidth: '120px',
      state: true,
      resultStateList: [{
        name: '未开始',
        value: 0,
      }, {
        name: '进行中',
        value: 1,
      }, {
        name: '已完成',
        value: 2,
      }],

      sigData: null,
      companyList: [],

      checkItems: [
        {
          //隐患问题
          name: '',
          //整改建议 - 附件
          reformProposalAttr: [],
          //整改期限
          rectifyDeadline: '',
          //整改结果【0 未开始 1 进行中 2 已完成
          resultState: 0,
        },
      ],

      form: {
        checkedId: '',
        checkTime: '',
        state: true,

        attachmentIdAttr: [],
        reportIdAttr: [],

      },
      rules: {
        checkedId: [{ required: true, message: '请选择企业名称', trigger: 'change' }],
        checkTime: [{ type: 'date', required: true, message: '请选择巡查时间', trigger: 'change' }],
        state: [{ required: true, message: '请选择巡查结果', trigger: 'change' }],

        attachmentIdAttr: [{ type: 'array', required: true, message: '请上传记录文件', trigger: 'blur' }],

      },
    };
  },
  created() {
    this.companyLists();
    this.getSig();
  },
  mounted() {},
  methods: {
    closeBox() {
      this.state = false;
      this.$ge.$emit('biz-check-change-search');
    },
    cancel(formName) {
      this.state = false;
      this.$refs[formName].resetFields();
    },
    handleRemove1(file, fileList) {
      this.form.attachmentIdAttr = fileList;
    },
    handleChange1(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.attachmentIdAttr = fileList;
      return false;
    },
    handleRemove2(file, fileList) {
      this.form.reportIdAttr = fileList;
    },
    handleChange2(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.reportIdAttr = fileList;
      return false;
    },
    handleRemoveDynamic(obj, res, fileList) {
      this.checkItems[obj.index].reformProposalAttr = fileList;
    },
    handleChangeDynamic(obj, res, fileList) {

      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = res.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.checkItems[obj.index].reformProposalAttr = fileList;
      return false;
    },
    //查询企业列表
    companyLists() {
      this.$get('/biz-company/list', {})
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.companyList = result.data;
          }
        })
        .catch((error) => {
          this.companyList = [];
        });
    },
    addItem() {
      this.checkItems.push({
        //隐患问题
        name: '',
        //整改建议 - 附件
        reformProposalAttr: [],
        //整改期限
        rectifyDeadline: '',
        //整改结果【0 未开始 1 进行中 2 已完成
        resultState: 0,
      });
    },
    delItem(index) {
      this.checkItems.splice(index, 1);
    },
    getSig() {
      this.$get('/oss/getUploadOssSignature')
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.sigData = result.data;
          }
        })
        .catch((error) => {
          this.sigData = null;
        });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$WLoading();
          //上传记录文件
          this.form.attachmentIdAttr = this.submitUpload(this.form.attachmentIdAttr);

          if (this.form.reportIdAttr && this.form.reportIdAttr.length > 0) {
            //上传整改报告
            this.form.reportIdAttr = this.submitUpload(this.form.reportIdAttr);
          }

          //上传不合格项文件
          if (!this.form.state) {
            this.form.checkItems = [];
            this.checkItems.forEach(element => {
              if (element.reformProposalAttr && element.reformProposalAttr.length > 0) {
                element.reformProposalAttr = this.submitUpload(element.reformProposalAttr);
              }
              this.form.checkItems.push(element);
            });
          }

          var param = {};
          param = Object.assign({}, this.form, param);

          this.$postJson('/biz-check/create', param)
            .then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);

                //关闭弹框并刷新列表
                this.closeBox(formName);
              } else this.$message.error(result.msg);
              this.$cancelLoading();
            })
            .catch((error) => {
              //添加用户异常
              this.$message.error('添加失败');
              this.$cancelLoading();
            });
        } else {
          return false;
        }
      });
    },
    submitUpload(allAttr) {

      let sigData = this.sigData;//提前请求拿到的签名信息

      let nowAllAttr = [];
      if (!allAttr || allAttr.length == 0)
        return nowAllAttr;

      allAttr.forEach(element => {
        let ossData = new FormData()//创建oss数据对象
        ossData.append('name', element.name)
        let keyValue = 'ep/web/' + this.uuid() + '::' + element.name
        ossData.append('key', keyValue)
        ossData.append('policy', sigData.policy)
        ossData.append('OSSAccessKeyId', sigData.accessId)
        ossData.append('success_action_status', 200)
        ossData.append('Signature', sigData.signature)
        ossData.append('file', element.raw)

        this.$postFormData(sigData.ossDomain, ossData)
          .then((result) => {})
          .catch((error) => {});

        nowAllAttr.push({
          name: element.name,
          url: sigData.ossDomain + '/' + keyValue,
          size: element.size,
        })
      });

      return nowAllAttr;
    },

  },
};
</script>

<style lang='scss' scoped>
.el-select {
  width: 100%;
}

.vue-treeselect__input {
  border: 0 !important;
}

.el-form-item__content {
  text-align: left;
}

/* 上传样式 start */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 上传样式 end */
</style>
